<?php
namespace Admin\Controller;
use Think\Controller;
use Admin\Controller\CommonController;

/**
 * 系统设置
 */
class SystemController extends CommonController {

	/**
	 * 职位管理
	 * @return [type] [description]
	 */
	public function job() {
		$name = I('get.name');
		if($name) {
			$map['name'] = $name;
		}

        $jobModel = M('Job');
        $total = $jobModel->where($map)->order('jid DESC')->count();
        $page = new \Think\Page($total, 10);
        $show = $page->show();

        $jobList = $jobModel->where($map)
                ->limit($page->firstRow .',' . $page->listRows)
                ->order('sort asc, jid DESC')
                ->select();       

        $this->assign('showpage', $show);
        $this->assign('jobList', $jobList);
        $this->display();
	}	

	/**
	 * 添加职位
	 * @return [type] [description]
	 */
	public function ajaxJobAdd() {
		if(IS_POST) {
			$jobModel = D('Job');

			if($jobModel->create()) {

				$res = $jobModel->add();
				if($res) {
					$message['status'] = 1;
					$message['msg'] = '添加成功';
					$this->ajaxReturn($message);					
				} else {
					$message['status'] = -1;
					$message['msg'] = '添加失败，请重试';
					$this->ajaxReturn($message);						
				}
			} else {
				$message['status'] = -1;
				$message['msg'] = $jobModel->getError();
				$this->ajaxReturn($message);
			}
		} else {
			throw new Exception("非法操作", 1);
		}
	}

	/**
	 * 获取职位数据
	 * @return [type] [description]
	 */
	public function ajaxJobData() {
		$jid = I('get.jid', 0);

		$info = M('Job')->where(array('jid' => $jid))->find();  
		if($info) {
			$message['status'] = 1;
			$message['info'] = $info;
		} else {
			$message['status'] = -1;
			$message['info'] = array();			
		}

		$this->ajaxReturn($message);
	}

	/**
	 * 编辑职位
	 * @return [type] [description]
	 */
	public function ajaxJobEdit() {
		if(IS_POST) {
			$jobModel = D('Job');

			if($jobModel->create()) {
				$res = $jobModel->save();
				if($res !== false) {
					$message['status'] = 1;
					$message['msg'] = '修改成功';
					$this->ajaxReturn($message);					
				} else {
					$message['status'] = -1;
					$message['msg'] = '修改失败，请重试';
					$this->ajaxReturn($message);						
				}
			} else {
				$message['status'] = -1;
				$message['msg'] = $jobModel->getError();
				$this->ajaxReturn($message);
			}
		} else {
			throw new Exception("非法操作", 1);
		}
	}

	/**
	 * 删除职位
	 * @return [type] [description]
	 */
	public function ajaxDelJob() {
		if(IS_GET) {
			$id = I('get.jid');
		} elseif(IS_POST) {
			$id = I('post.jid');
			is_array($id) && $id = implode(',', $id);
		}

		if(empty($id)) {
			$message['status'] = -1;
			$message['msg'] = '选项不能为空';
			$this->ajaxReturn($message);
		}

		$map['jid'] = array('in', $id);
		$res = M('Job')->where($map)->delete();
		if($res) {
			$message['status'] = 1;
			$message['msg'] = '删除成功';
			$this->ajaxReturn($message);			
		} else {
			$message['status'] = -1;
			$message['msg'] = '删除失败，请重试';
			$this->ajaxReturn($message);
		}
	}


	/**
	 * 频道列表
	 * @return [type] [description]
	 */
	public function channel() {
		$name = I('get.name');
		if($name) {
			$map['name'] = $name;
		}

        $channelModel = M('Channel');
        $total = $channelModel->where($map)->order('chid DESC')->count();
        $page = new \Think\Page($total, 22);
        $show = $page->show();

        $channelList = $channelModel->where($map)
                ->limit($page->firstRow .',' . $page->listRows)
                ->order('sort asc, chid DESC')
                ->select();       

        $userList = M('UserInfo')->field('realname, uid')->select();

        $this->assign('userList', $userList);
        $this->assign('showpage', $show);
        $this->assign('channelList', $channelList);
        $this->display();	
	}

	/**
	 * 添加频道
	 * @return [type] [description]
	 */
	public function ajaxChannelAdd() {
		if(IS_POST) {
			$channelModel = D('Channel');

			if($channelModel->create()) {

				$res = $channelModel->add();
				if($res) {
					$message['status'] = 1;
					$message['msg'] = '添加成功';
					$this->ajaxReturn($message);					
				} else {
					$message['status'] = -1;
					$message['msg'] = '添加失败，请重试';
					$this->ajaxReturn($message);						
				}
			} else {
				$message['status'] = -1;
				$message['msg'] = $channelModel->getError();
				$this->ajaxReturn($message);
			}
		} else {
			throw new Exception("非法操作", 1);
		}
	}

	/**
	 * 获取频道数据
	 * @return [type] [description]
	 */
	public function ajaxChannelData() {
		$chid = I('get.chid', 0);

		$info = M('Channel')->where(array('chid' => $chid))->find();  
		if($info) {
			$message['status'] = 1;
			$message['info'] = $info;
		} else {
			$message['status'] = -1;
			$message['info'] = array();			
		}

		$this->ajaxReturn($message);
	}

	/**
	 * 编辑频道
	 * @return [type] [description]
	 */
	public function ajaxChannelEdit() {
		if(IS_POST) {
			$channelModel = D('Channel');

			if($channelModel->create()) {
				$res = $channelModel->save();
				if($res !== false) {
					$message['status'] = 1;
					$message['msg'] = '修改成功';
					$this->ajaxReturn($message);					
				} else {
					$message['status'] = -1;
					$message['msg'] = '修改失败，请重试';
					$this->ajaxReturn($message);						
				}
			} else {
				$message['status'] = -1;
				$message['msg'] = $channelModel->getError();
				$this->ajaxReturn($message);
			}
		} else {
			throw new Exception("非法操作", 1);
		}
	}

	/**
	 * 删除频道
	 * @return [type] [description]
	 */
	public function ajaxDelChannel() {
		if(IS_GET) {
			$id = I('get.chid');
		} elseif(IS_POST) {
			$id = I('post.chid');
			is_array($id) && $id = implode(',', $id);
		}

		if(empty($id)) {
			$message['status'] = -1;
			$message['msg'] = '选项不能为空';
			$this->ajaxReturn($message);
		}

		$map['chid'] = array('in', $id);
		$res = M('Channel')->where($map)->delete();
		if($res) {
			$message['status'] = 1;
			$message['msg'] = '删除成功';
			$this->ajaxReturn($message);			
		} else {
			$message['status'] = -1;
			$message['msg'] = '删除失败，请重试';
			$this->ajaxReturn($message);
		}
	}

	public function notice() {
		$title = I('get.title');
		if($title) {
			$map['title'] = $title;
		}

        $noticeModel = M('Notice');
        $total = $noticeModel->where($map)->order('nid DESC')->count();
        $page = new \Think\Page($total, 20);
        $show = $page->show();

        $noticeList = $noticeModel->where($map)
                ->limit($page->firstRow .',' . $page->listRows)
                ->order('nid DESC')
                ->select();       

        // 所有频道
        $channels = M('Channel')->order('chid DESC')->select();

        // 所有职位
        $jobs = M('Job')->order('jid DESC')->select();

        $this->assign('showpage', $show);
        $this->assign('noticeList', $noticeList);
        $this->assign('channels', $channels);
        $this->assign('jobs', $jobs);
        $this->display();			
	}

	/**
	 * 添加公告
	 * @return [type] [description]
	 */
	public function ajaxNoticeAdd() {
		ini_set("max_execution_time", 0);
		if(IS_POST) {
			$noticeModel = D('Notice');

			$dataGet['title'] = I('post.title');
			$dataGet['content'] = I('post.content');
			$dataGet['channels'] = I('post.channels');


			$relation = array();
			if(is_array($dataGet['channels'])) {
				foreach($dataGet['channels'] as $key => $channel) {
					$relation[$channel] = I('post.jobs_' . $channel, array());
				}
			}

			$dataGet['relation'] = !empty($relation) ? serialize($relation) : '';

			if($noticeModel->create($dataGet)) {
				$time = time();
				$dataGet['createtime'] = $time;
				$dataGet['updatetime'] = $time;

				$res = $noticeModel->add($dataGet);
				if($res) {
					$uidList=array();
					// 向公告推送表中写入用户信息
					foreach($dataGet['channels'] as $k => $v) {

						//$ujob = implode(",", $v);
						$user_list = M('UserInfo')
						->field('ui.uid uid,clientid')
						->alias('ui')
						->join('__USER_LOGIN_INFO__ uli ON uli.uid=ui.uid')
						->order('uli.logintime DESC')
						->group('ui.uid')
						->where("userchannel={$v}")->select();
						foreach($user_list as $r){
							$data['nid'] = $res;
							$data['uid'] = $r['uid'];
							$uidList[]=$r['uid'];
							$data['createtime'] = time();
							M('NoticePush')->add($data);	
						}					
					}



					$trans=json_encode(array('pushCode'=>200,'objectId'=>$res,'userId'=>0));
		   			sock_post('http://localhost/Mapi/Tui/pushUidList.html', array('uids'=>$uidList,'title'=>'见微','content'=>'公告：'.I('post.content'),'trans'=>$trans));
					$message['status'] = 1;
					$message['msg'] = '添加成功';
					$this->ajaxReturn($message);					
				} else {
					$message['status'] = -1;
					$message['msg'] = '添加失败，请重试';
					$this->ajaxReturn($message);						
				}
			} else {
				$message['status'] = -1;
				$message['msg'] = $noticeModel->getError();
				$this->ajaxReturn($message);
			}
		} else {
			throw new Exception("非法操作", 1);
		}
	}

	/**
	 * 获取公告数据
	 * @return [type] [description]
	 */
	public function ajaxNoticeData() {
		$nid = I('get.nid', 0);

		$info = M('Notice')->where(array('nid' => $nid))->find();  
		if($info) {
			$info['relation'] = $info['relation'] ? unserialize($info['relation']) : array(); 
			$message['status'] = 1;
			$message['info'] = $info;
		} else {
			$message['status'] = -1;
			$message['info'] = array();			
		}

		$this->ajaxReturn($message);
	}


	/**
	 * 编辑公告
	 * @return [type] [description]
	 */
	public function ajaxNoticeEdit() {
		if(IS_POST) {
			$noticeModel = D('Notice');

			$dataGet['nid'] = I('post.nid');
			$dataGet['title'] = I('post.title');
			$dataGet['content'] = I('post.content');
			$dataGet['channels'] = I('post.channels');

			$relation = array();
			if(is_array($dataGet['channels'])) {
				foreach($dataGet['channels'] as $key => $channel) {
					$relation[$channel] = I('post.jobs_' . $channel, array());
				}
			}

			// print_r(I('post.'));exit;
			$dataGet['relation'] = !empty($relation) ? serialize($relation) : '';

			if($noticeModel->create($dataGet)) {
				$res = $noticeModel->save();
				if($res !== false) {
					$message['status'] = 1;
					$message['msg'] = '修改成功';
					$this->ajaxReturn($message);					
				} else {
					$message['status'] = -1;
					$message['msg'] = '修改失败，请重试';
					$this->ajaxReturn($message);						
				}
			} else {
				$message['status'] = -1;
				$message['msg'] = $noticeModel->getError();
				$this->ajaxReturn($message);
			}
		} else {
			throw new Exception("非法操作", 1);
		}
	}

	/**
	 * 删除公告
	 * @return [type] [description]
	 */
	public function ajaxDelNotice() {
		if(IS_GET) {
			$id = I('get.nid');
		} elseif(IS_POST) {
			$id = I('post.nid');
			is_array($id) && $id = implode(',', $id);
		}

		if(empty($id)) {
			$message['status'] = -1;
			$message['msg'] = '选项不能为空';
			$this->ajaxReturn($message);
		}

		$map['nid'] = array('in', $id);
		$res = M('Notice')->where($map)->delete();
		if($res) {
			$message['status'] = 1;
			$message['msg'] = '删除成功';
			$this->ajaxReturn($message);			
		} else {
			$message['status'] = -1;
			$message['msg'] = '删除失败，请重试';
			$this->ajaxReturn($message);
		}
	}


	public function workflow() {
		$chid = I('get.chid', 0);
		$info = M('Channel')->where(array('chid' => $chid))->find();

		if(!$info)
			$this->error('频道不存在');

		$relation = empty($info['relation']) ? array() : unserialize($info['relation']);

		$res = array();
		$n = 0;
		if($relation) {
			foreach($relation as $key => $val) {
			    $res[$n]['text'] = $key . '级审核';
			    $res[$n]['children'] = array();

				$map['uid'] = array('in', implode(',', $val));
				$tmp = M('UserInfo')->where($map)->select();

				if($tmp) {
					foreach($tmp as $k => $v) {
						$res[$n]['children'][$k]['uid'] = $v['uid'];
						$res[$n]['children'][$k]['text'] = $v['realname'];
					}
				}

				$n++;
			} 

		}

		$this->assign('chid', $chid);
		$this->assign('res', $res);
		$this->display();
	}

	/**
	 * 所有记者
	 * @return [type] [description]
	 */
	public function ajaxUserList() {
		$searchRealName = I('post.search_real_name');
		if($searchRealName)
			$map['realname'] = $searchRealName;
		$userList = M('UserInfo')->where($map)->select();

		$this->ajaxReturn($userList);
	}

	public function ajaxRelationByChannel() {
		$chid = I('get.chid', 0);
		$info = M('Channel')->where(array('chid' => $chid))->getField('relation');
		$info = empty($info) ? array() : unserialize($info);

		$res = array();
		$json['id'] = 0;
		$json['item'] = array();
		$json['open'] = 1;

		if($info) {

			foreach($info as $key => $val) {
				$json['item'][$key] = array(
					'id' => 'T_' . $key,
					'text' => ($key + 1) . '级审核',
					'child' => 1,
					'open' => 1,
					'item' => array(),
				);

				$map['uid'] = array('in', implode(',', $val));
				$tmp = M('UserInfo')->where($map)->select();

				foreach($tmp as $k => $v) {
					$json['item'][$key]['item'][$k] = array(
						'id' => $v['uid'],
						'text' => $v['realname'],		
					);
				}

			}
		} else {
			$json['item'][] = array(
				'id' => 'T_1',
				'text' => '1级审核',
				'child' => 1,
				'open' => 1,
				'item' => array(),
			);	
		}

		$this->ajaxReturn($json);

/*		/*$xml = '<?xml version="1.0" encoding="iso-8859-1"?><tree id="0">';
		if($info) {

			foreach($info as $key => $val) {
				$xml .= '<item text="' . $key . '级审核" id="p_' . $key . '">';

				$map['uid'] = array('in', implode(',', $val));
				$tmp = M('UserInfo')->where($map)->select();

				foreach($tmp as $k => $v) {
					$xml .= '<item text="' . $v['realname'] . '" id="id_' . $key . '_' . $key . '" />';
				}

				$xml .= '</item>';
			}
		} else {
				$xml .= '<item text="1级审核" id="p_1" />';		
		}
		$xml .= '</tree>';*/

		// $this->ajaxReturn(array('xml' => $xml, 'maxid' => $key));
	}
	

	// public function workFlowEdit() {
		// $chid = I('post.chid', 0);

		// $node = I('post.node', '');
		// $nodeSub = I('post.node_val_' . $node[0], '');
		// // print_r($_POST);exit;
		// if($node && $nodeSub) {
		// 	$arr[$node[0]] = $nodeSub; 
		// 	$dataGet['relation'] = serialize($arr);
		// 	$res = M('Channel')->where(array('chid' => $chid))->save($dataGet);
		// 	if($res !== false){
		// 		$message['status'] = 1;
		// 		$message['msg'] = '修改成功';
		// 		$this->ajaxReturn($message);
		// 	} else {
		// 		$message['status'] = -1;
		// 		$message['msg'] = '修改失败';
		// 		$this->ajaxReturn($message);			
		// 	}
		// } else {
		// 	$message['status'] = -1;
		// 	$message['msg'] = '数据不完整';
		// 	$this->ajaxReturn($message);			
		// }
	// }

	public function workFlowEdit() {
		$chid = I('post.chid', 0);
		$post = I('post.postarr', array());
		if(isset($post['item']) && !empty($post)) {
			$data = array();
			foreach($post['item'] as $key => $val) {
				if(isset($val['item']) && !empty($val['item'])) {
					foreach($val['item'] as $k => $r) {
						if(!($flag = stripos($r['id'], '_')))
							$data[$key][$k] = $r['id'];
						else 
							$data[$key][$k] = substr($r['id'], 0, $flag);
					}
				}
			}

			$dataGet['relation'] = serialize($data);
			
			$res = M('Channel')->where(array('chid' => $chid))->save($dataGet);

			if($res !== false){
				$message['status'] = 1;
				$message['msg'] = '修改成功';
				$this->ajaxReturn($message);
			} else {
				$message['status'] = -1;
				$message['msg'] = '修改失败';
				$this->ajaxReturn($message);			
			}
		} else {
			$message['status'] = -1;
			$message['msg'] = '数据不完整';
			$this->ajaxReturn($message);			
		}			

	}

	function menumange(){
		if(IS_POST){
			$arr=I("post.");
			$systemChannel=M('systemChannel');
			foreach($arr['scid'] as $v){
				$systemChannel
				->where(array('scid'=>$v))
				->save(array(
					'controllername'=>$arr['controller'][$v],
					'actionname'=>$arr['action'][$v],
					'icon'=>$arr['icon'][$v],
					'channelname'=>$arr['channelname'][$v],
					'sort'=>$arr['sortrank'][$v]
				));
			}
			$this->success("修改成功！",U('menumange'));

		}else{
			$type=M('SystemChannel')->order('sort ASC')->where(array('spid'=>0))->select();
	       foreach($type as $k=>$v){
	            $type[$k]['subMenu']=M('SystemChannel')->order('sort ASC')->where(array('spid'=>$v['scid']))->select();            
	       }
	       $this->assign("type",$type);
	       $this->display();
   		}
	}

	function post_add_sub(){
		if(IS_POST){
			$systemChannel=M('systemChannel');
			$id=$systemChannel->add(array(
				'controllername'=>I("post.controller"),
				'actionname'=>I("post.action"),
				'channelname'=>I("post.channelname"),
				'spid'=>I("post.spid")
			));
			$systemChannel->where(array('scid'=>$id))->save(array('sort'=>$id));
			$this->success("已经成功增加",U('menumange'));
		}
	}

	function get_del_column($id){
		if($id){
			$a=M('systemChannel')->find($id);
			M('systemChannel')->delete($id);
			M('systemChannel')->where(array('spid'=>$a['scid']))->delete($id);
			$this->success("已经成功删除",U('menumange'));
		}
	}

	function post_move_channel(){
		if(IS_POST){
			$systemChannel=M('systemChannel');
			$id=$systemChannel->save(array(
				'spid'=>I("post.spid"),
				'scid'=>I("post.scid")
			));
			$this->success("已经成功移动",U('menumange'));
		}
	}
}